package project.server.game;

import project.server.handlers.OutboundMessages;
import project.server.util.Logger;
import project.shared.messages.AnswerMessage;
import project.shared.player.Player;
import project.shared.util.Config;
import project.shared.messages.WinMessage;

public class GameHandler extends Thread {
	private OutboundMessages outQueue;
	private int gameId;
	private Player p1, p2, p3;
	private GameEndChecker check;
	private Config config;
	private Logger logger;
	private boolean game = true;
	private Player winner;
	
	public GameHandler(OutboundMessages outQueue, int gameId, Player p1, Player p2, Player p3, Logger logger, Config config){
		this.outQueue = outQueue;
		this.gameId = gameId;
		this.p1 = p1;
		this.p2 = p2;
		this.p3 = p3;
		this.logger = logger;
		this.config = config;
		start();
	}
	
	public void run(){
		check = new GameEndChecker();
		while(game){
			String answer = "VASTUS";
			outQueue.addMessage(new AnswerMessage(answer));
		}
		String gameRes = "Game " + gameId + " ended. ";
		if(winner == null){
			gameRes += "Tie game.";
		}else{
			gameRes += "Winner: " + winner.name;
		}
		logger.log(gameRes);
		outQueue.addMessage(createWinMessage()); 
	}
	
	
	private WinMessage createWinMessage() {
		return new WinMessage(winner, gameId);
	}
	
	
	public void sendAnswerMessageToServer(AnswerMessage msg){
		outQueue.addMessage(msg);
		
	}

	/**
	 * Sets the game false, ending the game.
	 */
	protected void gameEndsetter(){
		game = false;
	}
	
	/**
	 * Sets the winner.
	 *
	 * @param p the winner
	 */
	protected void setWinner(Player p){
		winner = p;
	}

}
